package com.byfan.barter.service.Impl;

import com.byfan.barter.entity.Commodity;
import com.byfan.barter.jpa.CommodityJpa;
import com.byfan.barter.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Author: FBY
 * @Description
 * @Version 1.0
 * @Date: 2021/5/14 18:03
 */
@Service
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    private CommodityJpa commodityJpa;

    @Override
    public Commodity save(Commodity commodity) {
        return commodityJpa.save(commodity);
    }

    @Override
    public Commodity getById(Integer id) {
        Optional<Commodity> optional =  commodityJpa.findById(id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Commodity> getAll() {
        Sort sort = Sort.by(Sort.Direction.DESC,"creatTime");
        List<Commodity> result = commodityJpa.findAll(sort);
        return result.isEmpty()?null:result;
    }

    @Override
    public List<Commodity> getByExample(Commodity commodity) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("openId",match -> match.exact())
                .withMatcher("title",match -> match.contains())
                .withMatcher("address",match -> match.contains())
                .withMatcher("school",match -> match.contains())
                .withMatcher("classify",match -> match.exact())
                .withMatcher("status",match -> match.exact())
                .withIgnoreNullValues()
                .withIgnorePaths("id");
        Example<Commodity> example = Example.of(commodity,matcher);
        Sort sort = Sort.by(Sort.Direction.DESC,"creatTime");
        List<Commodity> result = commodityJpa.findAll(example,sort);
        return result.isEmpty()?null:result;
    }

    @Override
    public void delete(Integer id) {
        commodityJpa.deleteById(id);
    }
}
